<?php

namespace App\Http\Controllers;

use App\Common\Constant\Params;
use App\Common\Constant\Status;
use App\Models\Order;
use App\Services\IOrderService;
use App\Services\ISessionService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;

class OrderController extends BaseController
{
    /**
     * 首页
     * @param Request $request
     */
    public function index(Request $request){
        return redirect(url('order/listMasterServing'));
    }
    
    /**
     * 待报价
     * @param Request $request
     */
    public function offeringList(Request $request,IOrderService $orderService){
        $listMatchingOffering = $orderService->listMatchingOffering(getCurrentUserid());
        return view('order/offeringList',['listMatchingOffering'=>$listMatchingOffering]);
    }

    /**
     * 我要报价
     */
    public function offer(Order $order, Request $request,IOrderService $orderService)
    {
        $orderService->loadOrderAllInfo($order);
        return view('order/offer',['order'=>$order]);
    }

    /**
     * 已报价详情
     */
    public function offered(Order $order, Request $request,IOrderService $orderService)
    {
        if ($order->myOffer->employed){
            return redirect(url("order/detail/{$order->id}"));
        }

        $orderService->loadOrderAllInfo($order);
        return view('order/offered',['order'=>$order]);
    }

    /**
     * 开始报价
     */
    public function offerStart(Order $order, Request $request,IOrderService $orderService)
    {
        if ($request->isMethod('post')){
            $orderService->giveOffer($order->id,getCurrentUserid(),$request->input('price'),$request->input('message'));
            return redirect(url('order/listmasteroffered'));
        }

        return view('order/offerStart',['order'=>$order,
            'offer_minimum'=>config('common.offer_minimum',10),
        ]);
    }

    /**
     * 师傅的已报价订单列表
     * @param $order_id
     * @param Request $request
     * @param IOrderService $orderService
     */
    public function listMasterOffered(Request $request,IOrderService $orderService)
    {
        $page = 1;
        $listMasterOffered = $orderService->listMasterOffered(getCurrentUserid(),$page);
        return view('order/listMasterOffered',['listMasterOffered'=>$listMasterOffered,'page'=>$page]);
    }

    /**
     * 师傅的服务中订单列表
     * @param Request $request
     * @param IOrderService $orderService
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function listMasterServing(Request $request,IOrderService $orderService)
    {
        $master_id = getCurrentUserid();
        $listMasterServing = $orderService->listMasterServing($master_id);
        $countServing = $orderService->countServing($master_id);
        $countFinished = $orderService->countFinished($master_id);
        $countAll = $orderService->countAll($master_id);
        return view('order/listMasterServing',['listMasterServing'=>$listMasterServing,'page'=>0,
            'countServing'=>$countServing,'countFinished'=>$countFinished,'countAll'=>$countAll
        ]);
    }

    /**
     * 师傅的已完成订单列表
     * @param Request $request
     * @param IOrderService $orderService
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function listMasterFinished(Request $request,IOrderService $orderService)
    {
        $master_id = getCurrentUserid();
        $listMasterFinished = $orderService->listMasterFinished($master_id);
        $countServing = $orderService->countServing($master_id);
        $countFinished = $orderService->countFinished($master_id);
        $countAll = $orderService->countAll($master_id);
        return view('order/listMasterFinished',['listMasterFinished'=>$listMasterFinished,'page'=>0,
            'countServing'=>$countServing,'countFinished'=>$countFinished,'countAll'=>$countAll
        ]);
    }

    /**
     * 师傅的全部订单列表，包括商家选定该师傅雇佣后所有正常状态、异常状态的订单
     * @param Request $request
     * @param IOrderService $orderService
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function listMasterAll(Request $request,IOrderService $orderService)
    {
        $master_id = getCurrentUserid();
        $page = 1;
        $listMasterAll = $orderService->listMasterAll($master_id,$page);
        $countServing = $orderService->countServing($master_id);
        $countFinished = $orderService->countFinished($master_id);
        $countAll = $orderService->countAll($master_id);
        return view('order/listMasterAll',['listMasterAll'=>$listMasterAll,'page'=>$page,
            'countServing'=>$countServing,'countFinished'=>$countFinished,'countAll'=>$countAll
        ]);
    }

    /**
     * 订单详情
     * @param $order_id
     * @param Request $request
     * @param IOrderService $orderService
     */
    public function detail(Order $order, Request $request,IOrderService $orderService)
    {
        if ($order->status->canceled || $order->status->closed){//取消或已退款陈功
            return redirect(url("order/except/{$order->id}"));
        }else if ($order->status->have_refund && $order->refund->refunding){//申请退款中
            return redirect(url("order/refund/{$order->id}"));
        }else if ($order->status->have_arbitrate && $order->refund->arbitrating){//客服仲裁中
            return redirect(url("order/refund/{$order->id}"));
        }else if ($order->status->have_refund && $order->refund->refund_agree){//已同意退款
            return redirect(url("refund/detail/{$order->refund->id}"));
        }else if ($order->status->have_arbitrate && $order->refund->arbitrate_agree){//已仲裁同意退款
            return redirect(url("refund/arbitrate/{$order->refund->id}"));
        }

        $orderService->loadOrderAllInfo($order);
        return view('order/detail',['order'=>$order]);
    }

    /**
     * 预约客户
     * @param $order_id
     * @param Request $request
     * @param IOrderService $orderService
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function appoint(Order $order, Request $request,IOrderService $orderService)
    {
        /**
         * 生成服务时间选项
         */
        $options = Collection::make([
            Carbon::today(),Carbon::today()->addDays(1),Carbon::today()->addDays(2),Carbon::today()->addDays(3),
            Carbon::today()->addDays(4),Carbon::today()->addDays(5),Carbon::today()->addDays(6),
            Carbon::today()->addDays(7),Carbon::today()->addDays(8),Carbon::today()->addDays(9),
        ])->mapWithKeys(function ($item) {
            if ($item->isToday()){
                $key = sprintf('今天(%s)',Params::$WEEKS[$item->format('N')]);
            }elseif ($item->isTomorrow()){
                $key = sprintf('明天(%s)',Params::$WEEKS[$item->format('N')]);
            }else{
                $key = sprintf('%s(%s)',$item->format('m月d日'),Params::$WEEKS[$item->format('N')]);
            }
            return [$key => [
                $item->addHours(8)->timestamp=>'8:00-10:00',
                $item->addHours(2)->timestamp=>'10:00-12:00',
                $item->addHours(2)->timestamp=>'12:00-14:00',
                $item->addHours(2)->timestamp=>'14:00-16:00',
                $item->addHours(2)->timestamp=>'16:00-18:00',
                $item->addHours(2)->timestamp=>'18:00-20:00',
            ]];
        });

        $orderService->loadOrderDetail($order);
        return view('order/appoint',['order'=>$order,'options'=>$options,
            'weeks'=>Params::$WEEKS,
        ]);
    }

    /**
     * 物流提货
     * @param Order $order
     * @param Request $request
     * @param IOrderService $orderService
     */
    public function delivery(Order $order, Request $request,IOrderService $orderService,ISessionService $sessionService)
    {
        if ($request->isMethod('post')){
            $orderService->delivery($order->id,$request->input('delivery_status'),array_filter($request->input('deliver_imgs')),$request->input('deliver_except'));
            return redirect($sessionService->getRefererUrl());
        }

        return view('order/delivery',['order'=>$order,
            'logistics_ok'=>Params::ORDER_MASTER_STATUS_LOGISTICS_OK,
            'logistics_failed'=>Params::ORDER_MASTER_STATUS_LOGISTICS_FAILED,
        ]);
    }

    /**
     * 确认完成服务
     * @param Order $order
     * @param Request $request
     * @param IOrderService $orderService
     * @param ISessionService $sessionService
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function finish(Order $order, Request $request,IOrderService $orderService,ISessionService $sessionService)
    {

        $orderService->loadOrderDetail($order);
        return view('order/finish',['order'=>$order]);
    }

    /**
     * 提交完成服务申请
     */
    public function applyFinish(Order $order, Request $request,IOrderService $orderService,ISessionService $sessionService)
    {
        if ($request->isMethod('post') && $request->has('confirm_code') && $request->has('confirm_code')){
            $ret = $orderService->verifyConfirmCode($request->input('order_id'),$request->input('confirm_code'));
            if (!$ret){
                return $this->renderFail(Status::ORDER_CONFIRM_CODE_WRONG);
            }
            $ret = $orderService->applyFinish($request->input('order_id'),array_filter($request->input('finish_imgs')),$request->input('finish_ticket_img'),$request->input('tmall_check_img'),$request->input('finish_message'));
            if ($ret){
                return view('order/applyFinish',[
                    'auto_pay_days'=>config('common.auto_pay_days'),
                    'auto_pay_date'=>Carbon::now()->addDays(7)->format('m月d日')]);
            }
        }
        return $this->renderFail(Status::ORDER_APPLY_FINISH_WRONG);
    }

    /**
     * 订单详情-退款状态
     * @param $order_id
     * @param Request $request
     * @param IOrderService $orderService
     */
    public function refund(Order $order, Request $request,IOrderService $orderService)
    {
        if ($order->status->canceled || $order->status->closed){//取消或已退款陈功
            return redirect(url("order/except/{$order->id}"));
        }else if (!$order->status->have_refund){//没有发起过退款申请
            return redirect(url("order/detail/{$order->id}"));
        }else if ($order->refund->refund_disagree && !$order->status->have_arbitrate){//不同意退款，也没发起过仲裁申请
            return redirect(url("order/detail/{$order->id}"));
        }else if ($order->refund->arbitrate_disagree){//仲裁不同意退款
            return redirect(url("order/detail/{$order->id}"));
        }

        $orderService->loadOrderAllInfo($order);
        return view('order/refund',['order'=>$order,'refund'=>$order->refund]);
    }

    /**
     * 订单异常详情页面
     * @param OrderRefund $refund
     * @param Request $request
     * @param IOrderService $orderService
     * @param IRefundService $refundService
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function except(Order $order, Request $request,IOrderService $orderService)
    {
        if (!$order->status->canceled && !$order->status->closed){
            return redirect(url("order/detail/{$order->id}"));
        }

        $orderService->loadOrderRefund($order);
        return view('order/except',['order'=>$order,]);
    }

    /**
     * 补款明细
     * @param Request $request
     */
    public function replenishList(Order $order,Request $request,IOrderService $orderService){
        $list = $orderService->replenishList($order->id);
        $total = $order->offer_price;
        foreach ($list as $row){
            $total += $row->replenish_amount;
        }
        return view('order/replenishList',['order'=>$order,'list'=>$list,'total'=>$total]);
    }

}
